package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    private final CategoryBrandService categoryBrandService;


    public BrandServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;

    }




    @Override
    public BrandDTO findBrandById(Long id) {
        return new BrandDTO(this.getById(id));
    }

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        //1.分页信息的健壮性处理
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);
        //2.分页
        Page<Brand> info = new Page<>(page, rows);
        //3.判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        //4.如果key存在，添加like和eq的查询条件，否则不添加
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(info);
        //5.封装结果
        List<Brand> list = info.getRecords();
        return new PageDTO<>(info.getTotal(), info.getPages(), BrandDTO.convertEntityList(list));

    }

    @Override
    public List<BrandDTO> listBrandByIds(List<Long> ids) {


        return BrandDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public List<BrandDTO> listBrandByCategory(Long cid) {

        //根据分类id查询中间表对象获取到品牌id集合，然后根据品牌的id集合查询对应的品牌集合
        List<CategoryBrand> categoryBrands = this.categoryBrandService
                .query()
                .eq("category_id", cid)
                .list();

        if (CollectionUtils.isEmpty(categoryBrands)) {
            throw new LyException(204, "当前分类没有关联品牌");
        }
        categoryBrands.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList());
        return listBrandByIds(categoryBrands.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList()));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);

        //品牌新增，完成后，主键回显id，根据回显的品牌id匹配提交的分类id，保存到中间表

        this.save(brand);
        if (CollectionUtils.isEmpty(brandDTO.getCategoryIds())){
            throw new LyException(400,"此品牌对应的分类不能为空");
        }
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());


    }

    private void saveCategoryBrand(List<Long> cids, Long bid) {
        //根据分类id集合和品牌id，组合出中间表对象集合
        List<CategoryBrand> categoryBrands=cids
                .stream()
                .map(cid->CategoryBrand.of(cid,bid))
                .collect(Collectors.toList());

        //保存中间表数据
        this.categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBrand(BrandDTO brandDTO) {

        //从dto转换为entity
        Brand brand=brandDTO.toEntity(Brand.class);
         this.updateById(brand);

         //品牌在修改过程中，分类是否发生了变化，1.变（变多了，变少了），2.没变

        //可以暴力操作，把之前的所有关系删除，然后重建关系

        //删除当前品牌对应的中间表的所有关系

        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>()
                                 .eq("brand_id",brand.getId()));


        //判断更应该入口处
        if (CollectionUtils.isEmpty(brandDTO.getCategoryIds())){
            throw new LyException(400,"此品牌对应的分类不能为空");
        }

        //重建品牌和分类的关系
        saveCategoryBrand(brandDTO.getCategoryIds(),brand.getId());
    }

    @Override
    public void deleteBrand(Long id) {
        this.removeById(id);
    }
}
